// cloudfunctions/bindUserDevice/index.js
'use strict';
exports.main = async (event, context) => {
  const db = uniCloud.database();
  const {
    user_id,
    device_id
  } = event;

  if (!user_id || !device_id) {
    return {
      success: false,
      error: 'user_id 和 device_id 不能为空'
    };
  }

  try {
    const now = Date.now();
    
    // 更新设备表的用户ID
    await db.collection('opendb-device')
      .where({
        device_id: device_id
      })
      .update({
        user_id: user_id,
        last_update_date: now
      });

    // 更新用户表的推送客户端ID
    await db.collection('linli-user')
      .where({
        userId: user_id
      })
      .update({
        push_clientid: device_id,
        last_device_update: now
      });

    console.log(`设备绑定成功: 用户 ${user_id} ↔ 设备 ${device_id}`);

    return {
      success: true,
      message: '设备绑定成功'
    };

  } catch (error) {
    console.error('设备绑定失败:', error);
    return {
      success: false,
      error: error.message
    };
  }
};